<template>
  <div class="product-list-page">
    <HeaderNav />
    
    <div class="container">
      <!-- 搜索和筛选区域 -->
      <div class="filter-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称、描述..."
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>

        <div class="filter-controls">
          <el-select
            v-model="filterForm.categoryId"
            placeholder="选择分类"
            clearable
            @change="handleSearch"
            style="width: 200px"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
            />
          </el-select>

          <el-select
            v-model="filterForm.sortBy"
            placeholder="排序方式"
            @change="handleSearch"
            style="width: 200px"
          >
            <el-option label="综合排序" value="default" />
            <el-option label="价格从低到高" value="price_asc" />
            <el-option label="价格从高到低" value="price_desc" />
            <el-option label="销量排序" value="sales" />
            <el-option label="最新上架" value="time" />
          </el-select>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="product-grid" v-loading="loading">
        <ProductCard
          v-for="product in productList"
          :key="product.id"
          :product="product"
        />
      </div>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && productList.length === 0"
        description="暂无商品"
      />

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="total"
        :page-sizes="[12, 24, 48, 96]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import HeaderNav from '@/components/HeaderNav.vue'
import ProductCard from '@/components/ProductCard.vue'
import { getProductList } from '@/api/product'
import { getCategoryList } from '@/api/category'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const searchKeyword = ref('')
const categories = ref([])
const productList = ref([])
const total = ref(0)

const filterForm = reactive({
  categoryId: null,
  sortBy: 'default'
})

const pagination = reactive({
  current: 1,
  size: 24
})

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      categories.value = res.data
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

// 加载商品列表
const loadProducts = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      keyword: searchKeyword.value || undefined,
      categoryId: filterForm.categoryId || undefined,
      status: 1 // 只显示上架商品
    }

    // 根据排序方式添加参数（后端需要支持排序）
    if (filterForm.sortBy === 'price_asc') {
      params.orderBy = 'price'
      params.orderType = 'asc'
    } else if (filterForm.sortBy === 'price_desc') {
      params.orderBy = 'price'
      params.orderType = 'desc'
    } else if (filterForm.sortBy === 'sales') {
      params.orderBy = 'sales_count'
      params.orderType = 'desc'
    } else if (filterForm.sortBy === 'time') {
      params.orderBy = 'create_time'
      params.orderType = 'desc'
    }

    const res = await getProductList(params)
    if (res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '加载商品列表失败')
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadProducts()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadProducts()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.current = page
  loadProducts()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 初始化
onMounted(() => {
  // 从路由参数获取筛选条件
  if (route.query.categoryId) {
    filterForm.categoryId = Number(route.query.categoryId)
  }
  if (route.query.keyword) {
    searchKeyword.value = route.query.keyword
  }
  
  loadCategories()
  loadProducts()
})
</script>

<style lang="scss" scoped>
.product-list-page {
  min-height: 100vh;
  background-color: #f5f7fa;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .filter-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .search-input {
      margin-bottom: 15px;
    }

    .filter-controls {
      display: flex;
      gap: 15px;
    }
  }

  .product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }

  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px;
    background: white;
    border-radius: 8px;
  }
}
</style>

